using System;
using System.Threading.Tasks;
using DotNetCore.CAP;
using Recommend.Api.Data;
using Recommend.Api.IntegrationEvents;
using Recommend.Api.Models;
using Recommend.Api.Models.Dtos;
using Recommend.Api.Services;

namespace Recommend.Api.IntegrationEventHandlers
{
    public class ProjectCreatedIntegrationEventHandler:ICapSubscribe
    {
        private readonly RecommendDbContext _recommendDbContext;
        private readonly IContactService _contactService;
        private readonly IUserService _userService;

        public ProjectCreatedIntegrationEventHandler(RecommendDbContext recommendDbContext,IContactService contactService, IUserService userService)
        {
            _recommendDbContext = recommendDbContext;
            _contactService = contactService;
            _userService = userService;
        }
        
        [CapSubscribe("projectapi.projectcreated")]
        public async Task CreateRecommendFromProjectAsync(ProjectCreatedIntegrationEvent @event)
        {

            //调用UserApi 服务，获取项目创建人信息
            var userInfo = await _userService.GetBaseUserInfoAsync(@event.UserId);

            //调用ContactApi 获取项目创建者的 好友信息
            var friendIds = await _contactService.GetContactsByUserIdAsync(@event.UserId);
           

            foreach (var item in friendIds)
            {
                var recommend = new ProjectRecommend
                {
                    FromUserId = @event.UserId,
                    Company = @event.Company,
                    Tags = @event.Tags,
                    ProjectId = @event.ProjectId,
                    FinStage = @event.FinStage,
                    ProjectAvatar = @event.ProjectAvatar,
                    CreatedTime = @event.CreatedTime,
                    Introduction = @event.Introduction,
                    RecommendType = EnumRecommendType.Friend,
                    RecommendTime = DateTime.Now,
                    FromUserAvatar = userInfo.Avatar,
                    FromUserName = userInfo.Name,
                    UserId = item.UserId
                };

                _recommendDbContext.ProjectRecommends.Add(recommend);
            }
            await  _recommendDbContext.SaveChangesAsync();           
           
        }
    }
}